<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.0.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.0.4">


  <link rel="mask-icon" href="/images/logo.svg?v=6.0.4" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.0.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  
  <meta name="keywords" content="php,thinkphp," />


<meta name="description" content="redirect方法，可以在自定义的控制器实现跳转的功能。看thinkphp 5.1源码发现它是在在jump trait中定义的一个方法。 Controller.php 12345678910111213141516171819202122232425...use traits\controller\Jump;class Controller&amp;#123;    use Jump;    /**">
<meta name="keywords" content="php,thinkphp">
<meta property="og:type" content="article">
<meta property="og:title" content="thinkphp5 “$this-&gt;redirect()” 到底经历了啥">
<meta property="og:url" content="http://blog.yunshu168.com/posts/9f373042.html">
<meta property="og:site_name" content="树下千云">
<meta property="og:description" content="redirect方法，可以在自定义的控制器实现跳转的功能。看thinkphp 5.1源码发现它是在在jump trait中定义的一个方法。 Controller.php 12345678910111213141516171819202122232425...use traits\controller\Jump;class Controller&amp;#123;    use Jump;    /**">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-12-04T11:25:35.739Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="thinkphp5 “$this-&gt;redirect()” 到底经历了啥">
<meta name="twitter:description" content="redirect方法，可以在自定义的控制器实现跳转的功能。看thinkphp 5.1源码发现它是在在jump trait中定义的一个方法。 Controller.php 12345678910111213141516171819202122232425...use traits\controller\Jump;class Controller&amp;#123;    use Jump;    /**">






  <link rel="canonical" href="http://blog.yunshu168.com/posts/9f373042.html"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>
  <title>thinkphp5 “$this->redirect()” 到底经历了啥 | 树下千云</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?f8a99180bb75f49a4b2206cab6e25c50";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <!-- <div class="headband"></div>
<a href="https://github.com/yunshu2009"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a> -->
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">树下千云</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>


  



 </div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.yunshu168.com/posts/9f373042.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="云舒">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="树下千云">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">thinkphp5 “$this->redirect()” 到底经历了啥</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <!--<span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>-->
              
                <!--<span class="post-meta-item-text">发表于</span>-->
              
              <!--<time title="创建于" itemprop="dateCreated datePublished" datetime="2018-04-07T23:04:01+08:00">2018-04-07</time>-->
            

            
            

            
          </span>

          

          
            
          

          
          

          


          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>redirect方法，可以在自定义的控制器实现跳转的功能。看thinkphp 5.1源码发现它是在在jump trait中定义的一个方法。</p>
<p>Controller.php</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">.</span><br><span class="line">.</span><br><span class="line">.</span><br><span class="line">use traits\controller\Jump;</span><br><span class="line"></span><br><span class="line">class Controller</span><br><span class="line">&#123;</span><br><span class="line">    use Jump;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 视图类实例</span><br><span class="line">     * @var \think\View</span><br><span class="line">     */</span><br><span class="line">    protected $view;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * Request实例</span><br><span class="line">     * @var \think\Request</span><br><span class="line">     */</span><br><span class="line">    protected $request;</span><br><span class="line"></span><br><span class="line">.</span><br><span class="line">.</span><br><span class="line">.</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<a id="more"></a>
<p>jump.php 可以看到它抛出一个异常</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php</span><br><span class="line"></span><br><span class="line">.</span><br><span class="line">.</span><br><span class="line">.</span><br><span class="line">namespace traits\controller;</span><br><span class="line"></span><br><span class="line">use think\Container;</span><br><span class="line">use think\exception\HttpResponseException;</span><br><span class="line">use think\Response;</span><br><span class="line">use think\response\Redirect;</span><br><span class="line"></span><br><span class="line">trait Jump</span><br><span class="line">&#123;</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    </span><br><span class="line">    protected function redirect($url, $params = [], $code = 302, $with = [])</span><br><span class="line">    &#123;</span><br><span class="line">        $response = new Redirect($url);</span><br><span class="line"></span><br><span class="line">        if (is_integer($params)) &#123;</span><br><span class="line">            $code   = $params;</span><br><span class="line">            $params = [];</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        $response-&gt;code($code)-&gt;params($params)-&gt;with($with);</span><br><span class="line"></span><br><span class="line">        throw new HttpResponseException($response);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">   .</span><br><span class="line">   .</span><br><span class="line">   .</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>查看<code>HttpResponseException</code>可以发现它是Excepton的子类</p>
<p>HttpResponseException.php</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php</span><br><span class="line">namespace think\exception;</span><br><span class="line"></span><br><span class="line">use think\Response;</span><br><span class="line"></span><br><span class="line">class HttpResponseException extends \RuntimeException</span><br><span class="line">&#123;</span><br><span class="line">    protected $response;</span><br><span class="line"></span><br><span class="line">    public function __construct(Response $response)</span><br><span class="line">    &#123;</span><br><span class="line">        $this-&gt;response = $response;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public function getResponse()</span><br><span class="line">    &#123;</span><br><span class="line">        return $this-&gt;response;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>RuntimeException</code>是SPL中的类,它继承<code>Exception</code><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">class RuntimeException extends Exception &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>到此我们知道了redirect()方法其实是抛出一个异常，那它是在哪里调用然后输出（跳转）呢？</p>
<p>从入口文件<code>index.php</code>开始。发现先加载<code>base.php</code>，然后执行App类的run方法。然后调用返回对象的send方法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php</span><br><span class="line">namespace think;</span><br><span class="line"></span><br><span class="line">// 加载基础文件</span><br><span class="line">require __DIR__ . &apos;/../thinkphp/base.php&apos;;</span><br><span class="line"></span><br><span class="line">// 支持事先使用静态方法设置Request对象和Config对象</span><br><span class="line"></span><br><span class="line">// 执行应用并响应</span><br><span class="line">Container::get(&apos;app&apos;)-&gt;run()-&gt;send();</span><br></pre></td></tr></table></figure>
<p><code>App</code>类,发现它catch了一个<code>HttpResponseException</code>，返回<code>Redirect</code>类型的Response 对象</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php</span><br><span class="line">namespace think;</span><br><span class="line"></span><br><span class="line">use think\exception\ClassNotFoundException;</span><br><span class="line">use think\exception\HttpResponseException;</span><br><span class="line">use think\route\Dispatch;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * App 应用管理</span><br><span class="line"> */</span><br><span class="line">class App implements \ArrayAccess</span><br><span class="line">&#123;</span><br><span class="line">    const VERSION = &apos;5.1.5&apos;;</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    </span><br><span class="line">    // 执行应用程序</span><br><span class="line">    public function run()</span><br><span class="line">    &#123;</span><br><span class="line">        // 初始化应用</span><br><span class="line">        $this-&gt;initialize();</span><br><span class="line"></span><br><span class="line">        try &#123;</span><br><span class="line">            if ($this-&gt;bind) &#123;</span><br><span class="line">                // 模块/控制器绑定</span><br><span class="line">                $this-&gt;route-&gt;bind($this-&gt;bind);</span><br><span class="line">            &#125; elseif ($this-&gt;config(&apos;app.auto_bind_module&apos;)) &#123;</span><br><span class="line">                // 入口自动绑定</span><br><span class="line">                $name = pathinfo($this-&gt;request-&gt;baseFile(), PATHINFO_FILENAME);</span><br><span class="line">                if ($name &amp;&amp; &apos;index&apos; != $name &amp;&amp; is_dir($this-&gt;appPath . $name)) &#123;</span><br><span class="line">                    $this-&gt;route-&gt;bind($name);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            // 读取默认语言</span><br><span class="line">            $this-&gt;lang-&gt;range($this-&gt;config(&apos;app.default_lang&apos;));</span><br><span class="line">            if ($this-&gt;config(&apos;app.lang_switch_on&apos;)) &#123;</span><br><span class="line">                // 开启多语言机制 检测当前语言</span><br><span class="line">                $this-&gt;lang-&gt;detect();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            $this-&gt;request-&gt;langset($this-&gt;lang-&gt;range());</span><br><span class="line"></span><br><span class="line">            // 加载系统语言包</span><br><span class="line">            $this-&gt;lang-&gt;load([</span><br><span class="line">                $this-&gt;thinkPath . &apos;lang/&apos; . $this-&gt;request-&gt;langset() . &apos;.php&apos;,</span><br><span class="line">                $this-&gt;appPath . &apos;lang/&apos; . $this-&gt;request-&gt;langset() . &apos;.php&apos;,</span><br><span class="line">            ]);</span><br><span class="line"></span><br><span class="line">            // 监听app_dispatch</span><br><span class="line">            $this-&gt;hook-&gt;listen(&apos;app_dispatch&apos;);</span><br><span class="line"></span><br><span class="line">            // 获取应用调度信息</span><br><span class="line">            $dispatch = $this-&gt;dispatch;</span><br><span class="line">            if (empty($dispatch)) &#123;</span><br><span class="line">                // 进行URL路由检测</span><br><span class="line">                $dispatch = $this-&gt;routeCheck();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            // 记录当前调度信息</span><br><span class="line">            $this-&gt;request-&gt;dispatch($dispatch);</span><br><span class="line"></span><br><span class="line">            // 记录路由和请求信息</span><br><span class="line">            if ($this-&gt;debug) &#123;</span><br><span class="line">                $this-&gt;log(&apos;[ ROUTE ] &apos; . var_export($this-&gt;request-&gt;routeInfo(), true));</span><br><span class="line">                $this-&gt;log(&apos;[ HEADER ] &apos; . var_export($this-&gt;request-&gt;header(), true));</span><br><span class="line">                $this-&gt;log(&apos;[ PARAM ] &apos; . var_export($this-&gt;request-&gt;param(), true));</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            // 监听app_begin</span><br><span class="line">            $this-&gt;hook-&gt;listen(&apos;app_begin&apos;);</span><br><span class="line"></span><br><span class="line">            // 请求缓存检查</span><br><span class="line">            $this-&gt;request-&gt;cache(</span><br><span class="line">                $this-&gt;config(&apos;app.request_cache&apos;),</span><br><span class="line">                $this-&gt;config(&apos;app.request_cache_expire&apos;),</span><br><span class="line">                $this-&gt;config(&apos;app.request_cache_except&apos;)</span><br><span class="line">            );</span><br><span class="line"></span><br><span class="line">            // 执行调度</span><br><span class="line">            $data = $dispatch-&gt;run();</span><br><span class="line"></span><br><span class="line">        &#125; catch (HttpResponseException $exception) &#123;</span><br><span class="line">            $data = $exception-&gt;getResponse();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        $this-&gt;middlewareDispatcher-&gt;add(function (Request $request, $next) use ($data) &#123;</span><br><span class="line">            // 输出数据到客户端</span><br><span class="line">            if ($data instanceof Response) &#123;</span><br><span class="line">                $response = $data;</span><br><span class="line">            &#125; elseif (!is_null($data)) &#123;</span><br><span class="line">                // 默认自动识别响应输出类型</span><br><span class="line">                $isAjax = $request-&gt;isAjax();</span><br><span class="line">                $type   = $isAjax ? $this-&gt;config(&apos;app.default_ajax_return&apos;) : $this-&gt;config(&apos;app.default_return_type&apos;);</span><br><span class="line"></span><br><span class="line">                $response = Response::create($data, $type);</span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                $response = Response::create();</span><br><span class="line">            &#125;</span><br><span class="line">            return $response;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        $response = $this-&gt;middlewareDispatcher-&gt;dispatch($this-&gt;request);</span><br><span class="line"></span><br><span class="line">        // 监听app_end</span><br><span class="line">        $this-&gt;hook-&gt;listen(&apos;app_end&apos;, $response);</span><br><span class="line"></span><br><span class="line">        return $response;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>继续看<code>Redirect</code>类父类<code>Response</code>的<code>send</code>方法。它设置了header头等</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php	</span><br><span class="line"></span><br><span class="line">namespace think;</span><br><span class="line"></span><br><span class="line">use think\response\Redirect as RedirectResponse;</span><br><span class="line"></span><br><span class="line">class Response</span><br><span class="line">&#123;</span><br><span class="line">     .</span><br><span class="line">     .</span><br><span class="line">     .</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 发送数据到客户端</span><br><span class="line">     * @access public</span><br><span class="line">     * @return void</span><br><span class="line">     * @throws \InvalidArgumentException</span><br><span class="line">     */</span><br><span class="line">    public function send()</span><br><span class="line">    &#123;</span><br><span class="line">        // 监听response_send</span><br><span class="line">        Container::get(&apos;hook&apos;)-&gt;listen(&apos;response_send&apos;, $this);</span><br><span class="line"></span><br><span class="line">        // 处理输出数据</span><br><span class="line">        $data = $this-&gt;getContent();</span><br><span class="line"></span><br><span class="line">        // Trace调试注入</span><br><span class="line">        if (Container::get(&apos;env&apos;)-&gt;get(&apos;app_trace&apos;, Container::get(&apos;app&apos;)-&gt;config(&apos;app.app_trace&apos;))) &#123;</span><br><span class="line">            Container::get(&apos;debug&apos;)-&gt;inject($this, $data);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        if (200 == $this-&gt;code &amp;&amp; $this-&gt;allowCache) &#123;</span><br><span class="line">            $cache = Container::get(&apos;request&apos;)-&gt;getCache();</span><br><span class="line">            if ($cache) &#123;</span><br><span class="line">                $this-&gt;header[&apos;Cache-Control&apos;] = &apos;max-age=&apos; . $cache[1] . &apos;,must-revalidate&apos;;</span><br><span class="line">                $this-&gt;header[&apos;Last-Modified&apos;] = gmdate(&apos;D, d M Y H:i:s&apos;) . &apos; GMT&apos;;</span><br><span class="line">                $this-&gt;header[&apos;Expires&apos;]       = gmdate(&apos;D, d M Y H:i:s&apos;, $_SERVER[&apos;REQUEST_TIME&apos;] + $cache[1]) . &apos; GMT&apos;;</span><br><span class="line"></span><br><span class="line">                Container::get(&apos;cache&apos;)-&gt;tag($cache[2])-&gt;set($cache[0], [$data, $this-&gt;header], $cache[1]);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        if (!headers_sent() &amp;&amp; !empty($this-&gt;header)) &#123;</span><br><span class="line">            // 发送状态码</span><br><span class="line">            http_response_code($this-&gt;code);</span><br><span class="line">            // 发送头部信息</span><br><span class="line">            foreach ($this-&gt;header as $name =&gt; $val) &#123;</span><br><span class="line">                header($name . (!is_null($val) ? &apos;:&apos; . $val : &apos;&apos;));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        $this-&gt;sendData($data);</span><br><span class="line"></span><br><span class="line">        if (function_exists(&apos;fastcgi_finish_request&apos;)) &#123;</span><br><span class="line">            // 提高页面响应</span><br><span class="line">            fastcgi_finish_request();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        // 监听response_end</span><br><span class="line">        Container::get(&apos;hook&apos;)-&gt;listen(&apos;response_end&apos;, $this);</span><br><span class="line"></span><br><span class="line">        // 清空当次请求有效的数据</span><br><span class="line">        if (!($this instanceof RedirectResponse)) &#123;</span><br><span class="line">            Container::get(&apos;session&apos;)-&gt;flush();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>最后应用终止时会执行<code>shutdown</code>处理方法。它在Error.php已经注册了shutdown方法为<code>Error</code>类的<code>appShutdown</code>方法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php</span><br><span class="line"> class Error</span><br><span class="line"> &#123;</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    public static function register()</span><br><span class="line">    &#123;</span><br><span class="line">        error_reporting(E_ALL);</span><br><span class="line">        set_error_handler([__CLASS__, &apos;appError&apos;]);</span><br><span class="line">        set_exception_handler([__CLASS__, &apos;appException&apos;]);</span><br><span class="line">        register_shutdown_function([__CLASS__, &apos;appShutdown&apos;]);</span><br><span class="line">    &#125;</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>appShutdown</code>方法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">public static function appShutdown()</span><br><span class="line">&#123;</span><br><span class="line">    if (!is_null($error = error_get_last()) &amp;&amp; self::isFatal($error[&apos;type&apos;])) &#123;</span><br><span class="line">        // 将错误信息托管至think\ErrorException</span><br><span class="line">        $exception = new ErrorException($error[&apos;type&apos;], $error[&apos;message&apos;], $error[&apos;file&apos;], $error[&apos;line&apos;]);</span><br><span class="line"></span><br><span class="line">        self::appException($exception);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    // 写入日志</span><br><span class="line">    Container::get(&apos;log&apos;)-&gt;save();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>OK.</p>
<p>另：thinkphp 5.0源码阅读参考：<a href="https://www.kancloud.cn/zmwtp/tp5/155311" target="_blank" rel="noopener">https://www.kancloud.cn/zmwtp/tp5/155311</a></p>

      
    </div>

    

    
    
    
<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">------本文结束<i class="fa fa-paw"></i>感谢阅读------</div>
    
</div>
  
</div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欣赏此文？求鼓励，求支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="云舒 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="云舒 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>云舒</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.yunshu168.com/posts/9f373042.html" title="thinkphp5 “$this->redirect()” 到底经历了啥">http://blog.yunshu168.com/posts/9f373042.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/php/" rel="tag"># php</a>
          
            <a href="/tags/thinkphp/" rel="tag"># thinkphp</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/e4000784.html" rel="next" title="数据库扩展">
                <i class="fa fa-chevron-left"></i> 数据库扩展
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/591736ba.html" rel="prev" title="公用短信服务设计">
                公用短信服务设计 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      
        <div id="gitment-container"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="云舒" />
            
              <p class="site-author-name" itemprop="name">云舒</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives">
                
                    <span class="site-state-item-count">68</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">28</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/yunshu2009" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:yunshu.luo@gmail.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.cnblogs.com/luoyunshu/" target="_blank" title="Cnblogs"><i class="fa fa-fw fa-globe"></i>Cnblogs</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.bilibili.com" target="_blank" title="bilibili"><i class="fa fa-fw fa-globe"></i>bilibili</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2012 &mdash; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">云舒</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Pisces</a></div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.4"></script>



  



	





  





  






<!-- LOCAL: You can save these files to your site and update links -->
    
        
         <!-- <link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css"> -->
        <!-- <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script> -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/default.css">
        <script src="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/gitment.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitment({
            id: decodeURI(window.location.pathname),
            owner: 'yunshu2009',
            repo: 'yunshu2009.github.io',
            
            oauth: {
            
            
                client_secret: '15cdd9dc30fb9e0c97260bf79fe09d158fa04b22',
            
                client_id: '9495da16cda475a5e221'
            }});
        gitment.render('gitment-container');
      }

      
      renderGitment();
      
      </script>
    






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  


</body>
</html>
